package com.dgut.uhrs.util;

import com.dgut.uhrs.bean.User;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

public class JWTUtil {
    private static long time = 1000*60*60*24;
    private static String userSignature = "user";
    private static String adminSignature = "admin";

    public static String createUserToken(User user){
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                //header
                .setHeaderParam("typ","jwt")
                .setHeaderParam("alg","HS256")
                //payload
                .claim("username",user.getName())
                .claim("role","user")
                .setSubject("user-test")
                .setExpiration(new Date(System.currentTimeMillis()+time))
                .setId(UUID.randomUUID().toString())
                //signature
                .signWith(SignatureAlgorithm.HS256,userSignature)
                .compact();
        return jwtToken;
    }

    public static String createAdminToken(){
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                //header
                .setHeaderParam("typ","jwt")
                .setHeaderParam("alg","HS256")
                //payload
                .claim("adminname","sakura")
                .claim("role","admin")
                .setSubject("admin-test")
                .setExpiration(new Date(System.currentTimeMillis()+time))
                .setId(UUID.randomUUID().toString())
                //signature
                .signWith(SignatureAlgorithm.HS256,adminSignature)
                .compact();
        return jwtToken;
    }

    public static Boolean userCheckToken(String token) {
        if (token == null) {
            return false;
        }
        JwtParser jwtParser = Jwts.parser();
        try {
            Jws<Claims> claimsJws = jwtParser.setSigningKey(userSignature).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static Boolean adminCheckToken(String token) {
        if (token == null) {
            return false;
        }
        JwtParser jwtParser = Jwts.parser();
        try {
            Jws<Claims> claimsJws = jwtParser.setSigningKey(adminSignature).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
